<template>
  <div>
    <div class="header" :class="{ hidden: isHidden }">
      <div class="header-content" :style="{ width: proxy.globalInfo.bodyWidth + 'px' }">
        <div class="logo" @click="goToHome">Tomorrow</div>

        <div class="menu">
          <span :class="['menu-item',-1 == currentPBoardId ? 'active':'']" @click="goToHome">首页</span>
          <template v-for="board in boardList" :key="board.boardId">
            <el-popover placement="bottom-start" :width="200" trigger="hover" v-if="board.children.length > 0">
              <template #reference>
                <span :class="['menu-item',board.boardId == currentPBoardId ? 'active':'']" @click="boardClickHandler(board)">{{ board.boardName }}</span>
              </template>
              <div class="sub-board-list">
                <span :class="['sub-board', subBoard.boardId == currentBoardId ? 'active' :'']" v-for="subBoard in board.children" :key="subBoard.boardId"  @click="subBoardClickHandler(subBoard)">
                  {{ subBoard.boardName }}
                </span>
              </div>
            </el-popover>
            <span :class="['menu-item',board.boardId == currentPBoardId ? 'active':'']" v-else  @click="boardClickHandler(board)">{{ board.boardName }}</span>
          </template>
        </div>

        

        <div class="auth-buttons">
          <div class="search-container">
            <el-input v-model="searchQuery" placeholder="Search..." class="search-bar">
              <template #suffix>
                <el-button :icon="Search" @click="handleSearch" circle></el-button>
              </template>
            </el-input>
            <el-button :icon="Plus" @click="goToPost" class="standalone-button">发帖</el-button>
          </div>
          
          <template v-if="userInfo.userId">
            <div class="user-info">
              <el-dropdown>
                <avatar :userId="userInfo.userId"></avatar>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>个人中心</el-dropdown-item>
                    <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            <div class="message-info">
              <el-dropdown>
                <el-badge value="99" class="item">
                  <div class="iconfont icon-message"></div>
                </el-badge>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>回复我的</el-dropdown-item>
                    <el-dropdown-item>点赞评论</el-dropdown-item>
                    <el-dropdown-item>点赞文章</el-dropdown-item>
                    <el-dropdown-item>下载附件</el-dropdown-item>
                    <el-dropdown-item>系统消息</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>

          <div class="joined-buttons" v-else>
            <el-button  @click="loginAndRegister(1)" class="joined-button">登录</el-button>
            <el-button @click="loginAndRegister(0)" class="joined-button">注册</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
  

  <!-- 文章列表 -->
  <div class="body-content">
    <router-view></router-view> 
  </div>

  <!-- 登录注册 -->
  <LoginAndRegister ref="loginAndRegisterRef"></LoginAndRegister>

</template>

<script setup>
import LoginAndRegister from './LoginAndRegister.vue';
import { ref, reactive, getCurrentInstance, onMounted ,watch} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { Plus, Search } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import LoginAndRegisterVue from './LoginAndRegister.vue';

const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const store = useStore();
const searchQuery = ref('');


// 新增退出登录函数

const handleLogout = async () => {
  try {
    // 调用后端登出接口
    const result = await proxy.Request({ 
      url: '/loginOut', 
      method: 'POST' 
    });

    // 后续处理保持不变
    window.location.reload()
    ElMessage.success('退出登录成功');
  } catch (error) {
    ElMessage.error('退出失败，请重试');
  }
};


const deleteCookie = (name) => {
  document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`; // 设置过期时间为过去，删除 Cookie
};

// 清空所有 Cookie（可选，根据需求选择清空单个或全部）
const clearAllCookies = () => {
  const cookies = document.cookie.split(';');
  for (const cookie of cookies) {
    const eqPos = cookie.indexOf('=');
    const name = eqPos > -1 ? cookie.substr(0, eqPos).trim() : cookie.trim();
    if (name) {
      document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
    }
  }
};

const api = {
  getUserInfo: '/getUserInfo', // 获取用户信息
  loadBoard: '/board/loadBoard' // 加载板块信息
};


//登录注册
const loginAndRegisterRef = ref();
const loginAndRegister = (type) => {
  loginAndRegisterRef.value.showPanel(type);
};

const captchaUrl = ref('/api/captcha'); // 假设这是你的验证码图片接口

const lastScrollPosition = ref(0);
const isHidden = ref(false);
const onScroll = () => {
  const currentScrollPosition = window.pageYOffset || document.documentElement.scrollTop;
  if (currentScrollPosition > 300 && currentScrollPosition > lastScrollPosition.value) {
    isHidden.value = true;
  } else {
    isHidden.value = false;
  }
  lastScrollPosition.value = currentScrollPosition;
};

onMounted(() => {
  // InfiniteScroll()
  getUserInfo();
});
//获取用户信息
const getUserInfo = async()=>{
  let result =await proxy.Request({
    url:api.getUserInfo,
  })
  if(!result){
    return;
  }
  store.commit('updateLoginUserInfo',result.data)
}
//获取板块信息
const boardList = ref([]);
const loadBoard = async()=>{
  let result = await proxy.Request({
    url:api.loadBoard,
  })
  if(!result){
    return;
  }
  boardList.value = result.data
  store.commit("saveBoardList",result.data)
}
loadBoard();

//监听用户信息
const userInfo = ref({})
watch(()=>store.state.loginUserInfo,(newVal,oldVal)=>{
  if(newVal != undefined && newVal != null){
    userInfo.value = newVal
  }else{
    userInfo.value = {}
  }
},{immediate : true , deep:true})
//监听是否显示登录面板
watch(()=>store.state.showLogin,(newVal,oldVal)=>{
  if(newVal){
    loginAndRegister(1);
  }
},{immediate : true, deep:true})

//当前选中的板块
const currentPBoardId = ref(0);
watch(()=>store.state.currentPBoardId,(newVal,oldVal)=>{
  if(newVal != undefined){
    currentPBoardId.value = newVal
  }
},{immediate : true})
const currentBoardId = ref(0);
watch(()=>store.state.currentBoardId,(newVal,oldVal)=>{
  if(newVal != undefined){
    currentBoardId.value = newVal
  }
},{immediate : true})

function handleSearch() {
  // 处理搜索逻辑
  console.log('Searching for:', searchQuery.value);
}

//回到首页
function goToHome() {
  router.push('/');
  currentPBoardId.value = -1;
}
//发帖
const goToPost=()=>{
  if(!store.getters.getLoginUserInfo){
    loginAndRegister(1);
  }else{
    router.push("/newPost")
  }
}

//板块点击
const boardClickHandler = (board)=>{
  router.push(`/forum/${board.boardId}`);
}

//二级模版
const subBoardClickHandler = (subBoard)=>{
  router.push(`/forum/${subBoard.pBoardId}/${subBoard.boardId}`);
}
</script>

<style lang="scss">
.header {
  width: 100%;
  position: fixed; /* 修改为fixed */
  top: 0; /* 固定在顶部 */
  height: 60px;
  background-color: #fff;
  box-shadow: 0 2px 6px 0 #ddd;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000; /* 确保它在其他内容之上 */
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  max-width: 1200px;
  padding: 0 20px;
  height: 100%;
}

.logo {
  width: 20%;
  font-size: 24px;
  font-weight: bold;
  cursor: pointer;
}

.menu {
  display: flex;
  gap: 10px;
  align-items: center;
  height: 100%;
  
  .menu-item {
    cursor: pointer;
    position: relative;
    transition: all 0.3s ease;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20px;
    &.home {
      text-decoration: none;
      color: inherit; // 确保颜色继承自 .menu-item
    }

    &.active::after,
    &:hover::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 2px;
      background-color: blue;
    }
    
  }
}

.sub-board-list {
  display: flex;
  flex-wrap: wrap;
  .sub-board {
    padding: 0px 10px;
    border-radius: 20px;
    margin-right: 10px;
    background: #ebebeb;
    border: 1px solid #e7e7e7;
    color: #585858;
    margin-top: 10px;
    cursor: pointer;
  }
  .sub-board:hover {
    color: var(--link);
  }
  .active{
    color: var(--link);
  }
}

.auth-buttons {
  display: flex;
  gap: 10px;
  width: 44%;
  align-items: center;
  .search-container {
    gap: 10px;
    margin-left: 50px;
    display: flex;
    
    .search-bar {
      flex-grow: 0;
      max-width: 200px;
      margin-left: 20px;
    }
    .standalone-button {
      padding: 8px 16px;
      border-radius: 4px;
      background-color: #007bff;
      color: #fff;
      cursor: pointer;

      &:hover {
        background-color: #0056b3;
      }
    }

  }
  .joined-buttons {
    display: flex;

    .joined-button {
      position: relative;
      padding: 8px 16px;
      border-radius: 0;
      background-color: #007bff;
      color: #fff;
      cursor: pointer;
      margin: 0;

      &:first-child {
        border-top-left-radius: 4px;
        border-bottom-left-radius: 4px;
      }

      &:last-child {
        border-top-right-radius: 4px;
        border-bottom-right-radius: 4px;
      }

      &:hover {
        background-color: #0056b3;
      }

      &::after {
        content: none;
      }
    }
  }
  .user-info {
    margin-left: 5px;
  }
  .message-info {
    .icon-message {
      font-size: 24px;
      color: #bfb9b9;
      cursor: pointer;
    }
  }
}

.body-content {
  position: relative;
  margin-top: 60px; /* 调整这个值以适应固定的header高度 */
  width: 100%;  
  align-items: center;
}



</style>